use std::error::Error;
use std::{env, fs};

pub struct Config {
    query: String,
    file_path: String,
    ignore_case: bool,
}

impl Config {
    pub fn build(args: &[String]) -> Result<Config, &'static str> {
        if args.len() < 3 {
            return Err("not enough args.")
        }
        let query = args[1].clone();
        let file_path = args[2].clone();

        let mut ignore_case = false;
        if env::var("IGNORE_CASE").is_ok() {
            ignore_case = str_to_bool(env::var("IGNORE_CASE").unwrap().as_str());
        } else if args.len() == 4 {
            ignore_case = str_to_bool(args[3].as_str());
        }

        Ok(Config {query, file_path, ignore_case})
    }
}

pub fn str_to_bool(v:&str) -> bool {
    match v.to_lowercase().as_str() {
        "true" => true,
        "1" => true,
        _ => false,
    }
}

pub fn run(config: Config) -> Result<(), Box<dyn Error>>{
    let content= fs::read_to_string(config.file_path)?;
    match config.ignore_case {
        true => {
            for line in search_ignore_case(&config.query, &content) {
                println!("{line}");
            }
        }
        false => {
            for line in search(&config.query, &content) {
                println!("{line}");
            }
        }
    }
    Ok(())
}

pub fn search<'a>(query: &'a str, content: &'a str) -> Vec<&'a str> {
    let mut result = Vec::new();
    for line in content.lines() {
        if line.contains(query) {
            result.push(line);
        }
    }
    result
}

pub fn search_ignore_case<'a>(query: &'a str, content: &'a str) -> Vec<&'a str> {
    let mut result = Vec::new();
    let query_lower:String = query.to_lowercase();
    for line in content.lines() {
        if line.to_lowercase().contains(query_lower.as_str()) {
            result.push(line);
        }
    }
    result
}


#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_search() {
        let query = "AB";
        let content = "AA AB CC
AABC
BB KOW
ANDABOENF ASSS";

        assert_eq!(vec!["AA AB CC","AABC", "ANDABOENF ASSS"], search(query, content));
    }
}